<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta property="og:type" content="website">
<meta property="og:title" content="vhuichen">
<meta property="og:url" content="https://vhuichen.github.io/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:locale">
<meta property="article:author" content="vhuichen">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":true,"isPost":false,"lang":"zh-Hans","comments":"","permalink":"","path":"index.html","title":""}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">vhuichen</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner index posts-expand">

    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2022/05/NetworkProtocol/KCP/KCP/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2022/05/NetworkProtocol/KCP/KCP/" class="post-title-link" itemprop="url">KCP 协议</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2022-05-19 00:00:00" itemprop="dateCreated datePublished" datetime="2022-05-19T00:00:00+08:00">2022-05-19</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-05-21 00:00:00" itemprop="dateModified" datetime="2022-05-21T00:00:00+08:00">2022-05-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%BD%91%E7%BB%9C%E5%8D%8F%E8%AE%AE/" itemprop="url" rel="index"><span itemprop="name">网络协议</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="什么是-KCP"><a href="#什么是-KCP" class="headerlink" title="什么是 KCP"></a>什么是 KCP</h3><p>我们知道 UDP 是不可靠传输， 而 TCP 是可靠传输，但 TCP 本身也存在一些缺陷，例如：  </p>
<ol>
<li>连续丢包超时策略，连续丢包的RTO &#x3D; RTO * 2，这个参数好像无法改动 ；  </li>
<li>丢包重传策略，在没有 SACK 之前，TCP在收到3个相同的 ack 时，才会触发丢包重传策略，并且会将后面所有的包全部重传（有些包其实已经收到了）；  </li>
<li>退流控制策略， 为了保证网络传输效率，TCP有发送窗口、接收窗口、慢启动、丢包退让策略，这样使得数据传输在一定程度上被阻塞了；  </li>
<li>延时ack</li>
<li>。。。。。。</li>
</ol>
<p>那除了 TCP 以外还有什么方式可以实现可靠性传输呢？就是 KCP ，KCP 本身只是一个算法实现，平台无关，并没有指定传输协议，所以通过 KCP + UDP 就可以实现跟 TCP 一样的可靠性传输；</p>
<h3 id="KCP-协议头"><a href="#KCP-协议头" class="headerlink" title="KCP 协议头"></a>KCP 协议头</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">0                 4     5     6          8  (BYTE)</span><br><span class="line">+-----------------+-----+-----+----------+  0</span><br><span class="line">|      conv       | cmd | frg |   wnd    |</span><br><span class="line">+-----------------+-----+-----+----------+  8</span><br><span class="line">|       ts        |         sn           |</span><br><span class="line">+-----------------+----------------------+  16</span><br><span class="line">|       una       |         len          |</span><br><span class="line">+-----------------+----------------------+  24</span><br><span class="line">|                                        |</span><br><span class="line">|            DATA (optional)             |</span><br><span class="line">|                                        |</span><br><span class="line">+----------------------------------------+</span><br></pre></td></tr></table></figure>
<h5 id="conv"><a href="#conv" class="headerlink" title="conv"></a>conv</h5><p>连接号，用于表示属于哪个连接  </p>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2022/05/NetworkProtocol/KCP/KCP/#more" rel="contents">
                Read more &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/" class="post-title-link" itemprop="url">libffi 探究</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2022-04-20 00:00:00" itemprop="dateCreated datePublished" datetime="2022-04-20T00:00:00+08:00">2022-04-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2021-04-22 00:00:00" itemprop="dateModified" datetime="2021-04-22T00:00:00+08:00">2021-04-22</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h4 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h4><p>自苹果禁用热更新以来（实际上就是禁用了 <code>dlsym</code> 等几个接口），使用了 JSpatch 等热更新库的应用也就无法更新了；<br>那么有没有一种方式可以代替通过 <code>dlsym</code> 实现的热更新呢？</p>
<h5 id="OCRunner-amp-MangoFix"><a href="#OCRunner-amp-MangoFix" class="headerlink" title="OCRunner &amp; MangoFix"></a>OCRunner &amp; MangoFix</h5><p>这两个库都可以实现 iOS 的热更新，使用的原理是相同的，都是通过语法分析、词法分析最终生成抽象语法树，再通过解析器解析，这里相当于自己写了一个编译器；而底层方法交换是通过 libffi  + runtime 实现的，这篇文章就来简单了解下 libffi 这个库的使用。</p>
<h4 id="libffi"><a href="#libffi" class="headerlink" title="libffi"></a>libffi</h4><p><code>FFI</code> 的全名是 Foreign Function Interface (外部函数接口)<br>libffi 提供了一套底层接口，在知道函数签名的情况下，可以根据相关接口完成函数调用；</p>
<h4 id="调用惯例-Calling-Convention"><a href="#调用惯例-Calling-Convention" class="headerlink" title="调用惯例(Calling Convention)"></a>调用惯例(Calling Convention)</h4><p>函数调用是通过堆栈体现出来的，在调用函数时，需要按照约定将相关的参数入栈，<br>而这种约定就叫做：调用惯例(Calling Convention)<br>也就是说只要我们按照这个约定存放函数调用时使用的参数，就可实现函数调用的效果；<br>libffi 也就是实现了这样的一个功能。</p>
<h3 id="libffi-调用任意-OC-方法"><a href="#libffi-调用任意-OC-方法" class="headerlink" title="libffi 调用任意 OC 方法"></a>libffi 调用任意 OC 方法</h3><p>实现步骤：  </p>
<ol>
<li>通过 libffi 创建 closure 闭包  </li>
<li>交换函数指针；之后调用原始方法，因为 imp 已经修改，最终会调用到闭包中  </li>
<li>在闭包回调函数里面，将 imp 替换成新的，将消息通过 ffi_call 发送出去</li>
</ol>
<p><strong>换句话说通过 libffi 的闭包功能，再加上 OC 提供给我们的 runtime ，一样也可以实现任意方法的 hook 功能；同时也为热修复提供了基础能力。</strong></p>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2022/04/iOS/libffi%E6%8E%A2%E7%A9%B6%20/#more" rel="contents">
                Read more &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2022/03/iOS/iOS%E5%AF%B9%E8%B1%A1%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E5%8A%A0%E5%85%A5%E8%87%AA%E5%8A%A8%E9%87%8A%E6%94%BE%E6%B1%A0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2022/03/iOS/iOS%E5%AF%B9%E8%B1%A1%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E5%8A%A0%E5%85%A5%E8%87%AA%E5%8A%A8%E9%87%8A%E6%94%BE%E6%B1%A0/" class="post-title-link" itemprop="url">ARC下，对象什么时候加入自动释放池</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2022-03-10 00:00:00" itemprop="dateCreated datePublished" datetime="2022-03-10T00:00:00+08:00">2022-03-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-03-11 00:00:00" itemprop="dateModified" datetime="2022-03-11T00:00:00+08:00">2022-03-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="ARC"><a href="#ARC" class="headerlink" title="ARC"></a>ARC</h3><p>ARC (Automatic Reference Counting) 是由编译器跟运行时共同完成的（运行时标记）；编译器会在编译时会自动加上 retain、release、autorelease、dealloc 操作。</p>
<h3 id="autoreleasing"><a href="#autoreleasing" class="headerlink" title="__autoreleasing"></a>__autoreleasing</h3><p>如果一个变量被用关键字修饰 __autoreleasing 修饰，那么变量会立即加入到自动释放池中</p>
<h3 id="ARC规则"><a href="#ARC规则" class="headerlink" title="ARC规则"></a>ARC规则</h3><ol>
<li><p>若方法名以下列词语开头，则其返回的对象归调用者所有：<br><code>alloc</code>  <code>new</code>  <code>copy</code>  <code>mutableCopy</code>。归调用者所有的意思是：调用上述四种方法的那段代码要负责释放方法所返回的对象。  </p>
</li>
<li><p>除了会自动调用“保留”与“释放”方法外，ARC 还可以执行一些手工操作很难甚至无法完成的优化。如果发现在同一个对象上执行多次“保留”与“释放”操作，那么ARC有时可以成对地移除这两个操作。<br>一般，在方法中返回自动释放的对象时，要执行一个特殊函数。此时不直接调用对象的 autorelease 方法，而是改为调用 objc_autoreleaseReturnValue 。此函数会检视当前方法返回之后即将要执行的那段代码。若发现那段代码在返回的对象上执行 retain 操作，则设置全局数据结构（此数据结构的具体内容因处理器而异）中的一个标志位而不执行 autorelease 操作。与之相似，如果方法返回了一个自动释放的对象，而调用方法的代码要保留此对象，那么此时不直接执行 retain，而是改为执行 objc_retainAutoreleaseReturnValue 函数。此函数要检测刚才提到的那个标志位，若已经置位，则不执行 retain 操作。设置并检测标志位，要比调用 autorelease 和 retain 更快。<br><strong>备注</strong>：objc_autoreleaseReturnValue 优化不一定开启，会根据不同CPU类型决定<br><strong>另外，这个标记位存在哪里呢？关键字：线程局部存储（TLS）</strong></p>
</li>
</ol>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2022/03/iOS/iOS%E5%AF%B9%E8%B1%A1%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E5%8A%A0%E5%85%A5%E8%87%AA%E5%8A%A8%E9%87%8A%E6%94%BE%E6%B1%A0/#more" rel="contents">
                Read more &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2022/01/NetworkProtocol/WebSocket/WebSocket/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2022/01/NetworkProtocol/WebSocket/WebSocket/" class="post-title-link" itemprop="url">WebSocket</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2022-01-23 00:00:00" itemprop="dateCreated datePublished" datetime="2022-01-23T00:00:00+08:00">2022-01-23</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-01-29 00:00:00" itemprop="dateModified" datetime="2022-01-29T00:00:00+08:00">2022-01-29</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%BD%91%E7%BB%9C%E5%8D%8F%E8%AE%AE/" itemprop="url" rel="index"><span itemprop="name">网络协议</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>Websocket 基于 TCP 的全双工通信协议，属于应用层协议，他必须依赖 HTTP 协议进行一次握手，握手成功后直接通过单个 TCP 传输数据。</p>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><ol>
<li>握手阶段使用HTTP连接；</li>
<li>可以发送文本，也可以发送二进制数据；</li>
<li>全双工通信；</li>
<li>协议标识符ws，加密是wss；</li>
</ol>
<h3 id="解决了什么问题"><a href="#解决了什么问题" class="headerlink" title="解决了什么问题"></a>解决了什么问题</h3><p>在没有 Websocket 之前，一般是通过 HTTP 轮询或者长轮询来实现数据推送  </p>
<ul>
<li>轮询：每隔一定时间发出一个请求，耗资源</li>
<li>长轮询：客户端发送一个超长时间的请求，服务器 hold 住这个请求，直到有新数据时返回</li>
</ul>
<p>这两种方式都比较耗资源，而 Websocket 可以很好的解决这类问题</p>
<h3 id="主要使用场景"><a href="#主要使用场景" class="headerlink" title="主要使用场景"></a>主要使用场景</h3><ol>
<li>股票行情推送</li>
<li>消息推送</li>
<li>IM聊天</li>
</ol>
<h2 id="握手流程"><a href="#握手流程" class="headerlink" title="握手流程"></a>握手流程</h2><p>通过 HTTP 连接，连接完成后用 TCP 通信</p>
<h3 id="请求头"><a href="#请求头" class="headerlink" title="请求头"></a>请求头</h3><p>客户端发起带有 Upgrade 字段的 Get 请求，请求头字段如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Connection: Upgrade</span><br><span class="line">Upgrade: websocket</span><br><span class="line">Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits</span><br><span class="line">Sec-WebSocket-Key: AAAAAAAA==</span><br><span class="line">Sec-WebSocket-Version: 13</span><br></pre></td></tr></table></figure>

<ol>
<li><strong>Connection</strong> ：表示要升级协议</li>
<li><strong>Upgrade</strong> ：要升级的协议是 websocket</li>
<li><strong>Sec-WebSocket-Extensions</strong> ：表示客户端所希望执行的扩展（如消息压缩插件）</li>
<li><strong>Sec-WebSocket-Key</strong> ：webSocket 协议校验值，服务端拼接一段固定字符串后加密返回回来，防止错误连接</li>
<li><strong>Sec-WebSocket-Version</strong> ：websocket 的版本</li></ol>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2022/01/NetworkProtocol/WebSocket/WebSocket/#more" rel="contents">
                Read more &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2021/10/NetworkProtocol/SRWebSocket/SRWebSocket/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2021/10/NetworkProtocol/SRWebSocket/SRWebSocket/" class="post-title-link" itemprop="url">SRWebSocket 源码解析</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-10-13 00:00:00" itemprop="dateCreated datePublished" datetime="2021-10-13T00:00:00+08:00">2021-10-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2021-10-24 00:00:00" itemprop="dateModified" datetime="2021-10-24T00:00:00+08:00">2021-10-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%BD%91%E7%BB%9C%E5%8D%8F%E8%AE%AE/" itemprop="url" rel="index"><span itemprop="name">网络协议</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="初始化流程"><a href="#初始化流程" class="headerlink" title="初始化流程"></a>初始化流程</h3><h5 id="id-initWithURLRequest-NSURLRequest-request-protocols-NSArray-protocols-allowsUntrustedSSLCertificates-BOOL-allowsUntrustedSSLCertificates"><a href="#id-initWithURLRequest-NSURLRequest-request-protocols-NSArray-protocols-allowsUntrustedSSLCertificates-BOOL-allowsUntrustedSSLCertificates" class="headerlink" title="- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates;"></a>- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates;</h5><p>初始化入口</p>
<h5 id="void-SR-commonInit"><a href="#void-SR-commonInit" class="headerlink" title="- (void)_SR_commonInit;"></a>- (void)_SR_commonInit;</h5><p>队列之类的数据初始化。<br>这里要说的是，SRWebSocket 内部创建一个常驻线程，用来接收数据流，还有一个专门用来处理业务的队列；当没有数据传输时常驻线程会进入休眠，此时队列任务发现<code>_readBuffer</code>没有数据，也会跳出循环等待，这样没有数据时也就不需要消耗多少资源了。</p>
<h5 id="void-initializeStreams"><a href="#void-initializeStreams" class="headerlink" title="- (void)_initializeStreams;"></a>- (void)_initializeStreams;</h5><p>初始化输入输出流</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">- (void)_initializeStreams &#123;</span><br><span class="line">    uint32_t port = _url.port.unsignedIntValue;</span><br><span class="line">    if (port == 0) &#123;</span><br><span class="line">        if (!_secure) &#123;</span><br><span class="line">            port = 80;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            port = 443;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    NSString *host = _url.host;</span><br><span class="line">    </span><br><span class="line">    CFReadStreamRef readStream = NULL;</span><br><span class="line">    CFWriteStreamRef writeStream = NULL;</span><br><span class="line">    //将 host port 与输入输出流绑定在一起</span><br><span class="line">    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &amp;readStream, &amp;writeStream);</span><br><span class="line">    </span><br><span class="line">    _outputStream = CFBridgingRelease(writeStream);</span><br><span class="line">    _inputStream = CFBridgingRelease(readStream);</span><br><span class="line">    </span><br><span class="line">    _inputStream.delegate = self;</span><br><span class="line">    _outputStream.delegate = self;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="连接流程"><a href="#连接流程" class="headerlink" title="连接流程"></a>连接流程</h3><h5 id="void-open"><a href="#void-open" class="headerlink" title="- (void)open;"></a>- (void)open;</h5><p>连接入口</p>
<h5 id="void-openConnection"><a href="#void-openConnection" class="headerlink" title="- (void)openConnection;"></a>- (void)openConnection;</h5><ol>
<li>将输入输出流注册到常驻线程</li>
<li>开启输入输出流</li>
</ol>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[_outputStream scheduleInRunLoop:aRunLoop forMode:mode];</span><br><span class="line">[_inputStream scheduleInRunLoop:aRunLoop forMode:mode];</span><br><span class="line">[_outputStream open];</span><br><span class="line">[_inputStream open];</span><br></pre></td></tr></table></figure>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2021/10/NetworkProtocol/SRWebSocket/SRWebSocket/#more" rel="contents">
                Read more &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2021/05/iOS/Modules/Modules/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2021/05/iOS/Modules/Modules/" class="post-title-link" itemprop="url">理解 iOS 中的 Modules</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-05-09 00:00:00" itemprop="dateCreated datePublished" datetime="2021-05-09T00:00:00+08:00">2021-05-09</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-09-04 11:07:17" itemprop="dateModified" datetime="2022-09-04T11:07:17+08:00">2022-09-04</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="什么是-Module"><a href="#什么是-Module" class="headerlink" title="什么是 Module"></a>什么是 Module</h1><p><code>module</code> 表示代码编译的最小模块，也就是一个<code>.m</code>文件编译成<code>.o</code>目标文件，那么这个<code>.o</code>就是一个 <code>module</code>。而 <code>modulemap</code> 可以将多个 <code>module</code> 合并成一个 <code>module</code>。<code>module</code> 还有另一个功能就是充当 Framework 中 OC 跟 Swift 的桥接文件。<br><code>module</code> 可以用来取代C&#x2F;C++预言传统的头文件引入方式，C&#x2F;C++ 中单个文件被引入了N次就需要编译N次，而使用 <code>module</code> 只需要1次。<br>而 <code>module</code>和头文件之间则是通过 <code>modulemap</code> 关联的</p>
<h3 id="include"><a href="#include" class="headerlink" title="#include"></a>#include</h3><p>include 使用不当会导致头文件重复导入。<br>预编译时会将 include 文件递归导入进.m文件，<br>假如有M个文件，每个文件都引入N个头文件，那么编译时间变为 M * N</p>
<h3 id="import"><a href="#import" class="headerlink" title="#import"></a>#import</h3><p>改进了 include ，可以防止重复添加头文件</p>
<h3 id="import-1"><a href="#import-1" class="headerlink" title="@import"></a>@import</h3><p>@import 导入的就是一个 <code>module</code> 的头文件。在使用 <code>module</code> 之前我们需要先打开这个功能</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Defines Module = YES</span><br><span class="line">Module Map File = &quot;手动创建的文件路径&quot; //可选</span><br></pre></td></tr></table></figure>

<p><strong>module到底有什么作用呢？</strong><br>module 会先把头文件编译成二进制文件，哪里需要使用这个头文件都会直接使用这个编译好的二进制头文件，除非这个头文件自身发生改动。<br>同一个头文件只需要编译一次就行了</p>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/2021/05/iOS/Modules/Modules/#more" rel="contents">
                Read more &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2021/04/iOS/Allocations/Allocations/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2021/04/iOS/Allocations/Allocations/" class="post-title-link" itemprop="url">Instruments 之 Allocations</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-04-24 00:00:00" itemprop="dateCreated datePublished" datetime="2021-04-24T00:00:00+08:00">2021-04-24</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-09-04 11:12:14" itemprop="dateModified" datetime="2022-09-04T11:12:14+08:00">2022-09-04</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="Allocations"><a href="#Allocations" class="headerlink" title="Allocations"></a>Allocations</h1><p><code>Allocations</code> 一般包含一个 <code>VM Tracker</code>，后面会简单介绍</p>
<h2 id="Statistics"><a href="#Statistics" class="headerlink" title="Statistics"></a>Statistics</h2><p>直译：统计 的意思<br>表示当前系统的内存占用列表  </p>
<img src="/2021/04/iOS/Allocations/Allocations/20210424230755.png" alt="img" style="zoom:50%;">

<h3 id="All-Heap-Allocation"><a href="#All-Heap-Allocation" class="headerlink" title="All Heap Allocation"></a>All Heap Allocation</h3><p>开发者手动申请的内存（堆），虚拟内存，这一部分是由开发者控制的。未使用的内存不会直接分配物理内存，只有使用了的内存才会在物理内存上分配空间。</p>
<h3 id="All-Anonymous-VM"><a href="#All-Anonymous-VM" class="headerlink" title="All Anonymous VM"></a>All Anonymous VM</h3><p>相对于<code>All Heap Allocation</code>，这里的是匿名的虚拟内存，开发者无法控制的内存。memory mapped file 、CALayer back store 好像都是在这里的</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">All Heap &amp; Anonymous VM 指的就是 All Heap Allocation + All Anonymous VM</span><br></pre></td></tr></table></figure>

<h3 id="VM-ImageIO-PNG-Data"><a href="#VM-ImageIO-PNG-Data" class="headerlink" title="VM:ImageIO_PNG_Data"></a>VM:ImageIO_PNG_Data</h3><p>使用 <code>[UIImage imageNamed:@&quot;*.png&quot;]</code> 缓存的解压后的图片</p>
<h3 id="VM-CG-raster-data"><a href="#VM-CG-raster-data" class="headerlink" title="VM:CG raster data"></a>VM:CG raster data</h3><p>通过CG解压的图片.光栅化数据，也就是像素数据</p>
<h2 id="Call-Tree"><a href="#Call-Tree" class="headerlink" title="Call Tree"></a>Call Tree</h2><p>显示调用函数，点击具体的函数能跳转到对应的代码</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Invert Call Tree 倒置函数栈</span><br><span class="line">Hide System Libraries 隐藏系统库</span><br></pre></td></tr></table></figure>

<h2 id="Allocations-list"><a href="#Allocations-list" class="headerlink" title="Allocations list"></a>Allocations list</h2><p>可以按照单次分配的内存大小排序，可以清楚的看到对应的调用栈  </p>
<img src="/2021/04/iOS/Allocations/Allocations/20210424231844.png" alt="img" style="zoom:50%;">

<h2 id="Generations"><a href="#Generations" class="headerlink" title="Generations"></a>Generations</h2><p>查看两个时间点之间的内存变化</p>
<h1 id="VM-Tracker"><a href="#VM-Tracker" class="headerlink" title="VM Tracker"></a>VM Tracker</h1><ul>
<li>打开界面后，需要先启动 <code>VM Tracker</code>  </li>
<li><img src="/2021/04/iOS/Allocations/Allocations/20210426171344.png" alt="img" style="zoom:33%;"></li>
</ul>
<img src="/2021/04/iOS/Allocations/Allocations/20210424232638.png" alt="img" style="zoom:50%;">  

<p><code>Resident</code> 指的是当前物理内存（已加载的代码段+脏内存）<br><code>VM Region</code> 一个 VM Region 是指一段连续的内存页（在虚拟地址空间里），这些页拥有相同的属性（如读写权限、是否是 wired，也就是是否能被 page out）<br><code>VMObject</code> 每个 VM Region 对应一个数据结构，名为 VM Object。 </p>
<p><code>% of Res.</code> 当前 Type 的 <code>Resident</code> 占 总 <code>Resident</code> 的比例<br><code>Type </code> 虚拟内存的类型<br><code># Regs</code> VM Region 的个数，也就是 VMObject 的个数？<br><code>Path</code> VM Region 从哪个文件映射过来的<br><code>Dirty Size</code> 脏内存，也就是系统无法回收的内存<br><code>Swapped Size</code> OSX 中被交换的内存。iOS 没有交换区，此时的<code>Swapped Size</code>就是压缩内存<br><code>Virtual Size</code>  虚拟内存总大小<br><code>Res. %</code> 当前物理内存占虚拟内存的总大小</p>
<img src="/2021/04/iOS/Allocations/Allocations/image-20220904111138382.png" alt="image-20220904111138382" style="zoom:50%;">

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2021/04/iOS/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2021/04/iOS/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/" class="post-title-link" itemprop="url">iOS内存管理机制</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-04-20 00:00:00" itemprop="dateCreated datePublished" datetime="2021-04-20T00:00:00+08:00">2021-04-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2022-09-04 11:14:37" itemprop="dateModified" datetime="2022-09-04T11:14:37+08:00">2022-09-04</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="0x00-内存分类"><a href="#0x00-内存分类" class="headerlink" title="0x00 内存分类"></a>0x00 内存分类</h1><p>根据不同 Section 可以将内存分为</p>
<ul>
<li>代码段 .text</li>
<li>已初始化数据段 .data</li>
<li>未初始化数据段 .bss</li>
<li>堆 heap </li>
<li>栈 stack</li>
</ul>
<img src="/2021/04/iOS/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/image-20220904111317704.png" alt="image-20220904111317704" style="zoom:50%;">

<p>根据内存能否被系统回收，可以分为</p>
<ul>
<li>Clean Memory</li>
<li>Dirty Memory</li>
</ul>
<h4 id="Clean-Memory"><a href="#Clean-Memory" class="headerlink" title="Clean Memory"></a>Clean Memory</h4><p>内存紧张时可以被覆盖，下次需要使用时，触发缺页中断，然后从磁盘加载到内存 （Page In）</p>
<ul>
<li>system framework</li>
<li>binary executable of your app</li>
<li>memory mapped files</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">疑问：链接的 framework 中 _DATA_CONST 并不绝对属于 clean memory，当 app 使用到 framework 时，就会变成 dirty memory。</span><br><span class="line">这里，嗯，没理解什么意思</span><br></pre></td></tr></table></figure>

<h4 id="Dirty-Memory"><a href="#Dirty-Memory" class="headerlink" title="Dirty Memory"></a>Dirty Memory</h4><p>无法被系统回收的内存，内存紧张时会给进程发送通知，需要程序手动释放这部分内存。同时系统会压缩这部分的内存，等下次使用时再解压。</p>
<ul>
<li>heap allocation</li>
<li>caches</li>
<li>decompressed images</li>
<li>compressed memory</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">虚拟内存</span><br><span class="line">Virtual Memory = Clean Memory + Dirty Memory  </span><br><span class="line">物理内存</span><br><span class="line">Resident Memory = Clean Memory(Loaded in Physical Memory) + Dirty Memory  </span><br><span class="line">实际内存占用</span><br><span class="line">memory footprint = dirty size + compressed size</span><br></pre></td></tr></table></figure>

<h1 id="0x01-内存管理"><a href="#0x01-内存管理" class="headerlink" title="0x01 内存管理"></a>0x01 内存管理</h1><p>内存管理可以分为两部分  </p>
<ul>
<li>APP内存管理，由APP内部控制</li>
<li>系统内存管理，由系统控制</li>
</ul>
<h2 id="APP内存管理"><a href="#APP内存管理" class="headerlink" title="APP内存管理"></a>APP内存管理</h2><p>APP管理方案有3中</p>
<h3 id="Tagged-Pointer"><a href="#Tagged-Pointer" class="headerlink" title="Tagged Pointer"></a>Tagged Pointer</h3><p>在64位的机器上，未引入 Tagged Pointer 之前内存结构如下图，对于一些很小的数据，在64位的机器下占用的内存翻了一倍，单单是指针就占用了2&#x2F;3的字节，同时还要在堆分配内存，维护引用计数等<br><img src="/2021/04/iOS/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/20210421192623.png" width="500"> </p>
<p>基于以上问题，苹果引入了 Tagged Pointer 对象，把一个对象的指针分为两部分，一部分作为数据标识，一部分存储数据。此时对象的指针不再是指针，更像是一个变量，并且不需要在堆中分配内存，这样不仅减少了占用内存，还提高了使用效率。<br><img src="/2021/04/iOS/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86%E6%9C%BA%E5%88%B6/image-20220904111357275.png" alt="image-20220904111357275" style="zoom:40%;"></p>
<p>Tagged Pointer 对象会在使用时创建，存放在栈区，同一个值每次创建都是同一个地址。<br>iOS默认开启了 Tagged Pointer 混淆，调试时设置 <code>OBJC_DISABLE_TAG_OBFUSCATION = YES</code> 后，数据正常了，每次APP启动后，都是同一个值</p>
<h4 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">NSNumber *num1 = @(7); //0x8000000000000393</span><br><span class="line">NSNumber *num2 = @(3); //0x8000000000000193</span><br></pre></td></tr></table></figure>
<p>低3位表示类标识<br>低4~7位表示数据类型<br>最高位表示是否是Tagged Pointer  </p>
<h3 id="Non-pointer-iSA"><a href="#Non-pointer-iSA" class="headerlink" title="Non-pointer iSA"></a>Non-pointer iSA</h3><p>在64位的架构下，指针查找数据并不需要64位，而苹果实际上只用33位来存储地址，剩下的用来存储一些其他的数据，iSA指针的结构如下  </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">// 注意真机和模拟器的结构是不一样的</span><br><span class="line">union isa_t </span><br><span class="line">&#123;</span><br><span class="line">    Class cls;</span><br><span class="line">    uintptr_t bits;</span><br><span class="line">    </span><br><span class="line">#   define ISA_MASK        0x0000000ffffffff8ULL</span><br><span class="line">#   define ISA_MAGIC_MASK  0x000003f000000001ULL</span><br><span class="line">#   define ISA_MAGIC_VALUE 0x000001a000000001ULL</span><br><span class="line">    struct &#123;</span><br><span class="line">        uintptr_t nonpointer        : 1; //是否开启 nonpointer </span><br><span class="line">        uintptr_t has_assoc         : 1; //关联对象</span><br><span class="line">        uintptr_t has_cxx_dtor      : 1; //表明对象是否有C++或ARC析构函数</span><br><span class="line">        uintptr_t shiftcls          : 33; // MACH_VM_MAX_ADDRESS 0x1000000000</span><br><span class="line">        uintptr_t magic             : 6;</span><br><span class="line">        uintptr_t weakly_referenced : 1; //弱引用</span><br><span class="line">        uintptr_t deallocating      : 1;</span><br><span class="line">        uintptr_t has_sidetable_rc  : 1;  //是否当前的引用计数过大</span><br><span class="line">        uintptr_t extra_rc          : 19; // 引用计数 = extra_rc + 1，超过就通过 SideTable 存储</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>是否使用 Non-pointer iSA 由苹果决定</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">1：包含swift代码</span><br><span class="line">2：sdk版本低于10.11</span><br><span class="line">3：runtime读取image时发现这个image包含__objc_rawisa段</span><br><span class="line">4：开发者自己添加了OBJC_DISABLE_NONPOINTER_ISA=YES到环境变量中</span><br><span class="line">5：某些不能使用Non-pointer的类，GCD等</span><br><span class="line">6：父类关闭</span><br></pre></td></tr></table></figure>

<h3 id="SideTables"><a href="#SideTables" class="headerlink" title="SideTables"></a>SideTables</h3><p>SideTables 是一个散列表， 用来管理对象的引用计数和弱引用。由于对象引用计数的操作是原子性操作所以 SideTable 中使用了自旋锁，SideTables 分成了8个 SideTable，实现了分离锁技术，提高了效率。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">struct SideTable &#123;</span><br><span class="line">	//非公平的自旋锁</span><br><span class="line">	spinlock_t slock;</span><br><span class="line">	//强引用相关，内部是一个hash表。</span><br><span class="line">	RefcountMap refcnts;</span><br><span class="line">	//弱引用相关，内部也是一个哈希表，每一个元素指向一个可变数组</span><br><span class="line">	weak_table_t weak_table;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>RefcountMap</code> 仅在未开启 isa 优化或 isa 优化情况下的引用计数溢出时才会用到  </li>
<li>8个 SideTable 可以一定程度上解决效率问题</li>
</ul>
<h2 id="系统内存管理"><a href="#系统内存管理" class="headerlink" title="系统内存管理"></a>系统内存管理</h2><p>当系统发现没有可用的内存页时，可能会有以下步骤  </p>
<ul>
<li>覆盖掉优先级较低的 Clean Memory ，以页为单位</li>
<li>给所有的前后台APP进程发送内存警告通知（一般APP会释放掉一些可以再次加载的内存）</li>
<li>通过上面两个步骤后，内存依然不够用，低内存管理机制 Jetsam 会根据优先级 kill 对应的进程</li>
</ul>
<h4 id="为什么手机APP容易被系统杀死，电脑APP不会被杀死，但却容易卡死"><a href="#为什么手机APP容易被系统杀死，电脑APP不会被杀死，但却容易卡死" class="headerlink" title="为什么手机APP容易被系统杀死，电脑APP不会被杀死，但却容易卡死"></a>为什么手机APP容易被系统杀死，电脑APP不会被杀死，但却容易卡死</h4><ul>
<li>电脑的 Swap 区在硬盘中，硬盘本身很大，很轻松的就虚拟出一个内存（虚拟内存）。机械硬盘不限读写次数，所以内存和硬盘之间可以无限读写。  </li>
<li>手机一般是用 flash 做存储器的，读写次数有限，如果用 flash 做 Swap 区，那么 flash 很可能在短时间内报废。所有手机一般都无 Swap 区。原因：1. flash 大小有限。2. flash 读写次数有限制</li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




  <nav class="pagination">
    <span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><span class="space">&hellip;</span><a class="page-number" href="/page/10/">10</a><a class="extend next" rel="next" href="/page/2/"><i class="fa fa-angle-right" aria-label="Next page"></i></a>
  </nav>

</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
